package cn.seocoo.platform.common.utils.upload;

import org.apache.commons.lang3.StringUtils;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class DownLoadFileUtil {

    public static boolean downLoadFile(HttpServletResponse response, Map<String, String> result,HttpServletRequest request) {
        String filename = result.get("filename");
        String filepathname = result.get("filepathname");
        if (StringUtils.isNotEmpty(filename) && StringUtils.isNotEmpty(filepathname)) {
            return DownLoadFileUtil.downLoadFile(response, filename, filepathname,request);
            // downLoadFile(filepathname, filename);
        }
        return false;
    }

    public static boolean downLoadFile(HttpServletResponse response, String fileName, String filePath, HttpServletRequest request) {
        try {
            String header = request.getHeader("User-Agent");
            File file = new File(filePath);
            if (!file.exists()) {
                return false;
            }
            if(header.contains("Firefox")){
                BASE64Encoder base = new BASE64Encoder();
                fileName = "=?utf-8?B?"+base.encode(fileName.getBytes("utf-8"))+"?=";
            }else{
                fileName = URLEncoder.encode(fileName,"utf-8");
            }
            // 读到流中
            InputStream inStream = new FileInputStream(filePath);// 文件的存放路径
            // 设置输出的格式
            //response.reset();
            //response.setContentType("bin");
            //response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);//注意这一步设置文件名时，中文容易出现乱码
            response.addHeader("Content-Length", "" + file.length());
            // 循环取出流中的数据
            byte[] b = new byte[1024];
            int len;
            try {
                while ((len = inStream.read(b)) > 0)
                    response.getOutputStream().write(b, 0, len);
                inStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return true;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     *
     * @param files  文件集合
     * @param response
     * @return
     * @throws Exception
     */
    public static HttpServletResponse downLoadFiles(List<File> files, String zipPathName, HttpServletResponse response) throws Exception {
        try {
            /**创建一个临时压缩文件，
             * 把文件流全部注入到这个文件中
             * 这里的文件你可以自定义是.rar还是.zip*/
            File file = new File(zipPathName);
            System.out.println("zipPath========>"+zipPathName);
            if (!file.exists()) {
                file.createNewFile();
            }
            //response.reset();
            //response.getWriter()
            //创建文件输出流
            FileOutputStream fous = new FileOutputStream(file);
            //打包的方法我们会用到ZipOutputStream这样一个输出流, 所以这里我们把输出流转换一下
            ZipOutputStream zipOut = new ZipOutputStream(fous);
            //这个方法接受的就是一个所要打包文件的集合，还有一个ZipOutputStream
            zipFile(files, zipOut);
            zipOut.close();
            fous.close();
            return downloadZip(file, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
        /**直到文件的打包已经成功了，
         * 文件的打包过程被我封装在FileUtil.zipFile这个静态方法中，
         * 稍后会呈现出来，接下来的就是往客户端写数据了*/
        return response;
    }

    public static void zipFile(List files, ZipOutputStream outputStream) {
        int size = files.size();
        for (int i = 0; i < size; i++) {
            File file = (File) files.get(i);
            zipFile(file, outputStream);
        }
    }

    public static HttpServletResponse downloadZip(File file, HttpServletResponse response) {
        try {
            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();

            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");

//如果输出的是中文名的文件，在此处就要用URLEncoder.encode方法进行处理
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getName(), "UTF-8"));
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
                File f = new File(file.getPath());
                f.delete();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return response;
    }

    public static void zipFile(File inputFile, ZipOutputStream ouputStream) {
        try {
            if (inputFile.exists()) {
                //如果是目录的话这里是不采取操作的
                if (inputFile.isFile()) {
                    FileInputStream IN = new FileInputStream(inputFile);
                    BufferedInputStream bins = new BufferedInputStream(IN, 512);
                    //org.apache.tools.zip.ZipEntry
                    /*int num = 1;
                    if (inputFile.exists()) {
                        inputFile.renameTo(new File(inputFile.getName() + num++));
                    }*/
                    ZipEntry entry = new ZipEntry(inputFile.getName());
                    ouputStream.putNextEntry(entry);
                    // 向压缩文件中输出数据
                    int nNumber;
                    byte[] buffer = new byte[512];
                    while ((nNumber = bins.read(buffer)) != -1) {
                        ouputStream.write(buffer, 0, nNumber);
                    }
                    // 关闭创建的流对象
                    bins.close();
                    IN.close();
                } else {
                    try {
                        File[] files = inputFile.listFiles();
                        for (int i = 0; i < files.length; i++) {
                            zipFile(files[i], ouputStream);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
